package com.probiz.estore.system.service.dwr;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.acegisecurity.Authentication;
import org.acegisecurity.context.HttpSessionContextIntegrationFilter;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;

import com.probiz.estore.Constants;
import com.probiz.estore.cart.CheckoutConstants;
import com.probiz.estore.common.model.customer.Customer;
import com.probiz.estore.common.model.system.AppUser;
import com.probiz.estore.common.service.LoginNtService;
import com.probiz.estore.customer.service.CustomerManager;
import com.probiz.estore.webapp.util.RequestContext;
import com.probiz.estore.webapp.util.RequestUtil;

/**
 * only for front estroe customer login window( ajax type)
 * 
 * 
 */
public class LoginDwr {
	private CustomerManager customerManager ;
	
	public void setCustomerManager(CustomerManager customerManager) {
		this.customerManager = customerManager;
	}
	
	private LoginNtService loginNtService;
	
	public void setLoginNtService(LoginNtService loginNtService) {
		this.loginNtService = loginNtService;
	}


	/**
	 * 检查结帐过程是否超时.
	 * 
	 * @param request
	 * @return true表示已经超时,session中已经没有checkoutModel;
	 */
	public boolean isCheckoutTimeout(HttpServletRequest request) {
		if (request.getSession().getAttribute(CheckoutConstants.CHECKOUT_ON) == null)
			return true;
		return false;
	}

	/**
	 * 取到当前登录用户
	 */
	public Integer getCurrentAppUserId(HttpServletRequest request, HttpServletResponse response) {
		Integer appUserId = RequestContext.getCurrentUserId();
		// 非匿名用户（已经login的用户）才记录userid和username入cookies.
		if (!Constants.USERID_ANONYMOUS.equals(appUserId)) {
			RequestUtil.setUserIdCookie(response, RequestContext.getCurrentUserId(), (request).getContextPath());
			RequestUtil.setUserNameCookie(response, RequestContext.getCurrentUser().getUsername(), (request).getContextPath());
		}
		return appUserId;
	}

	public String _getLoginStatus(HttpServletRequest request, HttpServletResponse response, String username, String password) {

		Customer customer = customerManager.getCustomer4Login(username, password);

		if (null != customer) {
			Authentication authRequest = new UsernamePasswordAuthenticationToken(customer, password);
			SecurityContext securityContext = SecurityContextHolder.getContext();
			if (securityContext != null) {
				securityContext.setAuthentication(authRequest);
				request.getSession().setAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY, securityContext);
			}
			loginNtService.afterLogin(request, response, (AppUser)customer);
			return "success";
		}else{
			return "failure";
		}

	}
	

}
